#!/usr/bin/env python

import sys

import minuit
import numpy
from matplotlib import pyplot
import tables

from charmicat import BadCommandLineError

import ypipi

def main():
    '''
    ypipi_fit_Y2S.py [opts] file.h5 

    Bin events in `file.h5' and attempt to fit the Upsilon(2S). 
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    opts, args = op.parse_args()

    if len(args) == 0:
        msg = 'Please supply an input file.'
        raise BadCommandLineError(msg, -1)
    
    with tables.openFile(args[0]) as fp:
        data = fp.root.nt[:]['mm_off_pi0pi0']

    h = ypipi.hists['mm_off_pi0pi0_Y2S'] 

    h.fill(data)
    
    x     = map(h.bin_center, range(h.nbins))
    y     = h.bins()
    y_unc = numpy.sqrt(y)

    pyplot.errorbar(x, y, yerr=y_unc, fmt='r.')
    pyplot.xlabel(r'MM($\pi^0\pi^0$) GeV')
    pyplot.ylabel(r'Counts per 100 keV')
    pyplot.title("Missing Mass of $\pi^0\pi^0$")

    path_out = args[0].rsplit('.', 1)[0] + '_fit.png'
    pyplot.savefig(path_out)

    return 0
    
    

if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
